//
//  TOConversationListViewController.m
//  IMChat
//
//  Created by CLSgGhost on 2021/6/18.
//  Copyright © 2021年 TeamOne. All rights reserved.
//

#import "TOConversationListViewController.h"

@interface TOConversationListViewController()<RCIMUserInfoDataSource,
                                              RCIMGroupInfoDataSource>

@end

@implementation TOConversationListViewController


//将要布局子视图
-(void)viewWillLayoutSubviews{
    // 显示底部tabBar
    self.tabBarController.tabBar.hidden = NO;
    // 未读消息显示
    int unReadCount = [[RCIMClient sharedRCIMClient] getUnreadCount:@[@(ConversationType_PRIVATE),
                        @(ConversationType_GROUP)]];
    if(unReadCount != 0){
        self.tabBarItem.badgeValue = [NSString stringWithFormat:@"%d",unReadCount];
    }else{
        self.tabBarItem.badgeValue = nil;
    }
}

//已经布局子视图
-(void)viewDidLayoutSubviews{
    //self.tabBarController.tabBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 设置用户信息代理
    [RCIM sharedRCIM].userInfoDataSource = self;
    // 设置群组信息代理
    [[RCIM sharedRCIM] setGroupInfoDataSource:self];
    //设置用户信息子本地持久化存储。SDK获取过的用户信息将保存着数据库中，即使APP重启也能再次读取
    [RCIM sharedRCIM].enablePersistentUserInfoCache = YES;
    
    //设置会话列表@(ConversationType_SYSTEM)
    [self setDisplayConversationTypes:@[@(ConversationType_PRIVATE),
                                        @(ConversationType_DISCUSSION),
                                        @(ConversationType_CHATROOM),
                                        @(ConversationType_GROUP)
                                        ]];
    
    //导航栏右侧搜索按钮
    UIBarButtonItem *searchBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch
                             target:self
                             action:@selector(searchInfo:)];
    
    //导航栏右侧加号按钮
    UIBarButtonItem *addBtn = [[UIBarButtonItem alloc]
         initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                              target:self
                              action:@selector(moreActions:)];
    //更改颜色
    addBtn.tintColor = [UIColor colorWithRed:0.502 green:0.502 blue:1 alpha:1.00];
    searchBtn.tintColor = [UIColor colorWithRed:0.502 green:0.502 blue:1 alpha:1.00];
    
    NSArray *actionButtonItems = @[addBtn, searchBtn];
    self.navigationItem.rightBarButtonItems = actionButtonItems;
    
}

//点击搜索按钮
-(void)searchInfo:(id)sender{
    
    NSLog(@"你点击了搜索按钮！！");
}

//点击加号按钮
-(void)moreActions:(UIBarButtonItem *)sender {
    
    NSLog(@"你点击了加号按钮！！");
    
    NSArray *titleArray = @[@"发起群聊",
                            @"添加朋友",
                            @"发起单聊"];
    
    NSArray *imageArray = @[@"start_group_chat",
                            @"add_friend",
                            @"start_group_chat"];
    
    CGPoint pt = CGPointMake(400,75);
    
    ZWPullMenuView *moreActionsMenuView = [ZWPullMenuView pullMenuAnchorPoint:pt
                                                             titleArray:titleArray
                                                             imageArray:imageArray];
    moreActionsMenuView.zwPullMenuStyle = PullMenuDarkStyle;
    moreActionsMenuView.blockSelectedMenu = ^(NSInteger menuRow){
        if(menuRow == 0){
            NSLog(@"发起群聊");
            GroupChatViewController *gcvc = [[GroupChatViewController alloc]init];
            gcvc.title = @"选择联系人";
            self.tabBarController.tabBar.hidden = YES;
            [self.navigationController pushViewController:gcvc animated:YES];
            
        }else if(menuRow == 1){
            NSLog(@"添加好友");
            NewFriendTableViewController *newFriendVC = [[NewFriendTableViewController alloc]init];
            newFriendVC.title = @"新的朋友";
            //移除通讯录提示小红点，ItemIndex:1 就是第二个tabBar
            [self.tabBarController.tabBar hideBadgeOnItemIndex:1];
            self.tabBarController.tabBar.hidden = YES;
            [self.navigationController pushViewController:newFriendVC animated:YES];
        }else{
            NSLog(@"发起单聊");
            TOConversationViewController *conversationVC = [[TOConversationViewController alloc] init];
            conversationVC.conversationType = ConversationType_PRIVATE;
            conversationVC.targetId = @"test";
            
            // 隐藏底部tarbar
            self.tabBarController.tabBar.hidden = YES;
            
            [self.navigationController pushViewController:conversationVC animated:YES];
        }
    };
}

// 即将显示Cell的回调，可以在此回调中修改Cell的一些显示属性。
- (void)willDisplayConversationTableCell:(RCConversationBaseCell *)cell atIndexPath:(NSIndexPath *)indexPath {
 
}

// 会话列表cell点击事件
- (void)onSelectedTableRow:(RCConversationModelType)conversationModelType
         conversationModel:(RCConversationModel *)model
               atIndexPath:(NSIndexPath *)indexPath {
    
    TOConversationViewController *conversationVC = [[TOConversationViewController alloc]initWithConversationType:model.conversationType targetId:model.targetId];
    
    conversationVC.conversationType = model.conversationType;
    conversationVC.targetId = model.targetId;
    conversationVC.title = model.conversationTitle;
    
    //可以获取历史信息，消息存储先不做了
    NSArray *historyMessage = [[RCIMClient sharedRCIMClient]getHistoryMessages:model.conversationType targetId:model.targetId oldestMessageId:-1 count:20];
    
    for(RCMessage *message in historyMessage){
        if([message.objectName isEqualToString:@"RC:TxtMsg"]){
            RCTextMessage *textMessaage = (RCTextMessage *)message.content;
            NSLog(@"获得历史消息：%@",textMessaage.content);
        }
    }
    
    // 隐藏底部tabBar
    self.tabBarController.tabBar.hidden = YES;
    
    [self.navigationController pushViewController:conversationVC animated:YES];
}

//自定义会话列表cell（好友请求cell）
- (void)didReceiveMessageNotification:(NSNotification *)notification{
    
    [super didReceiveMessageNotification:notification];
    
    // 未读消息显示(只统计私聊、群组消息个数)
    int unReadCount = [[RCIMClient sharedRCIMClient] getUnreadCount:@[@(ConversationType_PRIVATE),
                         @(ConversationType_GROUP)]];
    dispatch_async(dispatch_get_main_queue(),^{
        if(unReadCount != 0){
            // 设置提示红点数
            self.tabBarItem.badgeValue = [NSString stringWithFormat:@"%d",unReadCount];
        }
    });
    
    NSLog(@"收到消息了！！！！！！");
    
    RCMessage *message = notification.object;
    
    // 拦截好友请求消息
    if([message.content isMemberOfClass:[RCContactNotificationMessage class]]){

        NSLog(@"消息n类型：%lu",(unsigned long)message.conversationType);
        
        RCContactNotificationMessage *contactNtfMessage = [[RCContactNotificationMessage alloc] init];
        contactNtfMessage = (RCContactNotificationMessage *)message.content;
        NSLog(@"收到消息了！！！userId:%@",contactNtfMessage.operation);
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            dispatch_async(dispatch_get_main_queue(),^{
                //设置通讯录提示小红点，ItemIndex:1 就是第二个tabBar
                [self.tabBarController.tabBar showBadgeOnItemIndex:1];
                /** 获得全局变量. */
                AppDelegate *myDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
                
                [TOAFHttpUtils findNewFiendRequestInfo:myDelegate.userId];
            });
        });
        
        
        //[self refreshConversationTableViewWithConversationModel:contactNtfModel];
    }
}

// 实现用户信息提供者的代理函数
- (void)getUserInfoWithUserId:(NSString *)userId
                   completion:(void (^)(RCUserInfo *))completion {

    [TOAFHttpUtils findUserById:userId
                      withBlock:^(UserInfoModel * _Nonnull userModel) {
                          
                          //NSLog(@"-----会话列表里面:%@",userModel.userId);
                          RCUserInfo *userInfo = [[RCUserInfo alloc]
                                                  initWithUserId:userModel.userId
                                                  name:userModel.userName
                                                  portrait:userModel.userPortraitUri];
                          if (completion) {
                              completion(userInfo);
                          }
                      }];
    
}

// 实现群组信息提供者的代理函数
- (void)getGroupInfoWithGroupId:(NSString *)groupId
                     completion:(void (^)(RCGroup *))completion{
    
    [TOAFHttpUtils findGroupInfoById:groupId
           block:^(GroupInfoModel * _Nonnull groupModel) {
        
               RCGroup *group = [[RCGroup alloc]initWithGroupId:groupModel.groupId groupName:groupModel.groupName portraitUri:@""];
                                   
            if (completion) {
                completion(group);
            }
    }];
    
}

//将要消失
-(void)viewWillDisappear:(BOOL)animated{
    // 隐藏底部tabBar
    //self.tabBarController.tabBar.hidden = YES;
}

//已经消失
-(void)viewDidDisappear:(BOOL)animated{
    // 隐藏底部tabBar
    //self.tabBarController.tabBar.hidden = YES;
}

@end

